package tree;

import java.util.ArrayList;
import java.util.List;

public class SumRootToLeafNumbers129 {
    public int sumNumbers(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        dfs(root, 0, result);
        return result.stream().reduce((a, b) -> a + b).get();
    }

    private void dfs(TreeNode root, int cur, List<Integer> result) {
        if (root == null) {
            return;
        }
        if (root.left != null) {
            int ccur = cur * 10 + root.val;
            dfs(root.left, ccur, result);
        }

        if (root.right != null) {
            int ccur = cur * 10 + root.val;
            dfs(root.right, ccur, result);
        }

        if (root.left == null && root.right == null) {
            cur = cur * 10 + root.val;
            result.add(cur);
        }
    }
}
